package xyf.p10.dp;

/**
 * ClassName: P0416_CanPartition
 * Description:
 * Author: xyf
 * Date: 9/9/22 10:24 AM
 * Version: 1.0
 **/
public class P0416_CanPartition
{
    public boolean canPartition(int[] nums)
    {
        int sum = 0;
        for (int i = 0; i < nums.length; i++)
        {
            sum += nums[i];
        }

        if (sum % 2 != 0)
        {
            return false;
        }

        int target = sum / 2;

        boolean[][] dp = new boolean[nums.length][target + 1];

        for (int i = 0; i < nums.length; i++)
        {
            dp[i][0] = true;
        }

        for (int i = 1; i <= target; i++)
        {
            if (i == nums[0])
            {
                dp[0][i] = true;
            }
        }

        for (int i = 1; i < nums.length; i++)
        {
            for (int j = 1; j < target + 1; j++)
            {
                if (nums[i] > target)
                {
                    return false;
                }
                if (j >= nums[i])
                {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]];
                }
                else
                {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[nums.length - 1][target];
    }
}
